#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   文件名称 :     __init__.py
   文件功能描述 :   功能描述
   创建人 :       小钟同学
   创建时间 :          2021/12/13
-------------------------------------------------
   修改描述-2021/12/13:         
-------------------------------------------------
"""
import typing
from grpc_interceptor import ServerInterceptor
from grpc_interceptor.exceptions import GrpcException
from typing import Any, Callable, NamedTuple, Tuple
import abc
import grpc
from grpcframe.zyxgrpc.compose_app import ComposeApp
from typing import Any, Dict, Tuple


# 需要先继承ServerInterceptor再继承ABCMeta
class FlaskRequestMiddleware(ServerInterceptor, ComposeApp):

    def intercept(self, method: Callable, request: Any, context: grpc.ServicerContext, method_name: str, ) -> Any:
        # 创建上下文对象
        ctx = None
        if self.app:
            ctx = self.app.request_context(request, context)
        try:
            # 上下文入栈
            if self.app:
                ctx.push()
            # 回调调用必要的前置的函数处理
            response = method(request, context)
            return response
        except GrpcException as e:
            context.set_code(e.status_code)
            context.set_details(e.details)
            raise
        finally:
            if self.app:
                ctx.pop()
